using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
namespace AppToolKit.Data
{
	public abstract class CommandBuilderBase
	{
		public DbCommandQuery Format(string synatx, Dictionary<string, object> dict)
		{
			DbCommandQuery query = new DbCommandQuery();
			string pattern = "\\$\\{(?<key>.*?)\\}";
			Regex regex = new Regex(pattern, RegexOptions.Compiled);
			query.Query = regex.Replace(synatx, delegate(Match match)
			{
				string result;
				if (match.Groups["key"].Success)
				{
					string value = match.Groups["key"].Value;
					if (!dict.ContainsKey(value))
					{
						throw new FormatException(string.Format("key({0})不包含在dict中", value));
					}
					result = this.DoNamedProcess(dict, value, query);
				}
				else
				{
					result = string.Empty;
				}
				return result;
			}
			);
			return query;
		}
		protected abstract string DoNamedProcess(Dictionary<string, object> dict, string key, DbCommandQuery query);
		public DbCommandQuery Format(string synatx, params object[] args)
		{
			DbCommandQuery query = new DbCommandQuery();
			query.CommandType = CommandType.Text;
			string pattern = "\\{(?<key>\\d+)\\}";
			Regex regex = new Regex(pattern, RegexOptions.Compiled);
			query.Query = regex.Replace(synatx, delegate(Match match)
			{
				string result;
				if (match.Groups["key"].Success)
				{
					string value = match.Groups["key"].Value;
					if (Convert.ToInt32(value) < 0 || Convert.ToInt32(value) > args.Length - 1)
					{
						throw new IndexOutOfRangeException();
					}
					result = this.DoNumberProcess(value, args, query);
				}
				else
				{
					result = string.Empty;
				}
				return result;
			}
			);
			return query;
		}
		protected abstract string DoNumberProcess(string key, object[] args, DbCommandQuery query);
	}
}
